<template>
  <div class="comment-container">
    <!-- 地图容器 -->
    <div id="commentMapView" class="comment-map-view"></div>

    <!-- 景点列表面板按钮 -->
    <div class="feature-panel-button" @click="showSpotListPanel = true">
      <el-icon>
        <List />
      </el-icon>
    </div>

    <!-- 景点列表面板 -->
    <el-drawer v-model="showSpotListPanel" title="景点列表" direction="rtl" size="350px" :with-header="false"
      class="custom-drawer">
      <div class="drawer-header">
        <h2>景点评价</h2>
        <el-icon class="close-button" @click="showSpotListPanel = false">
          <Close />
        </el-icon>
      </div>
      <div class="search-box">
        <el-input v-model="searchKeyword" placeholder="搜索景点名称" prefix-icon="Search" clearable></el-input>
      </div>
      <el-scrollbar height="calc(100vh - 180px)">
        <div class="spot-list">
          <div v-for="spot in filteredSpots" :key="spot.OBJECTID" class="spot-item"
            :class="{ active: selectedSpot?.OBJECTID === spot.OBJECTID }" @click="selectSpot(spot)">
            <div class="spot-info">
              <div class="spot-name">{{ spot.SpotName }}</div>
              <div class="spot-type">
                <el-tag size="small" :type="getTypeTagType(spot.SpotType)">
                  {{ getTypeLabel(spot.SpotType) }}
                </el-tag>
              </div>
            </div>
            <div class="spot-rating" v-if="spotRating[spot.OBJECTID]">
              <el-rate v-model="spotRating[spot.OBJECTID]" disabled text-color="#ff9900" score-template="{value}">
              </el-rate>
              <div class="average-rating">平均评分: {{ spotRating[spot.OBJECTID].toFixed(1) }}</div>
            </div>
            <div class="spot-rating" v-else>
              <span class="no-rating">暂无评分</span>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </el-drawer>

    <!-- 评论面板 -->
    <el-drawer v-model="showCommentPanel" title="景点评价" direction="rtl" size="400px" :with-header="false"
      class="custom-drawer" :before-close="handleCommentPanelClose">
      <template v-if="selectedSpot">
        <div class="drawer-header">
          <h2>{{ selectedSpot.SpotName }} - 评价</h2>
          <el-icon class="close-button" @click="showCommentPanel = false">
            <Close />
          </el-icon>
        </div>

        <div class="spot-detail">
          <div v-if="selectedSpot.IntroduceImageBase64" class="spot-image">
            <img :src="selectedSpot.IntroduceImageBase64" alt="景点图片" />
          </div>
          <div class="spot-description">
            <p>{{ selectedSpot.SpotIntroduction || '暂无介绍' }}</p>
          </div>
        </div>

        <!-- 评论列表 -->
        <div class="comments-section" v-if="spotComments.length > 0">
          <h3>游客评价 ({{ spotComments.length }})</h3>
          <el-scrollbar height="200px">
            <div class="comment-list">
              <div v-for="(comment, index) in spotComments" :key="index" class="comment-item">
                <div class="comment-header">
                  <div class="user-info">
                    <el-avatar :size="32" :icon="UserFilled"></el-avatar>
                    <span class="username">{{ comment.username }}</span>
                  </div>
                  <div class="comment-rating">
                    <el-rate v-model="comment.rating" disabled text-color="#ff9900"></el-rate>
                  </div>
                </div>
                <div class="comment-content">{{ comment.content }}</div>
                <div class="comment-time">{{ formatDate(comment.timestamp) }}</div>
              </div>
            </div>
          </el-scrollbar>
        </div>
        <div class="no-comments" v-else>
          <el-empty description="暂无评价" />
        </div>

        <!-- 添加评论表单 -->
        <div class="add-comment-section">
          <h3>添加您的评价</h3>
          <el-form :model="commentForm" label-position="top">
            <el-form-item label="评分">
              <el-rate v-model="commentForm.rating" show-score text-color="#ff9900" score-template="{value}分"></el-rate>
            </el-form-item>
            <el-form-item label="评价内容">
              <el-input v-model="commentForm.content" type="textarea" :rows="4" placeholder="请分享您的游览体验..."
                maxlength="200" show-word-limit></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitComment" :disabled="!canSubmit">
                提交评价
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { List, Search, UserFilled, Close } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

// 用户信息
const userStore = useUserStore()

// 地图和图层
let view: __esri.MapView
let attractionsLayer: __esri.FeatureLayer

// 定义用户数据接口
interface UserData {
  comments: Array<{
    username: string;
    rating: number;
    content: string;
    timestamp: number;
  }>;
  averageRating?: number;
}

// UI 状态
const showSpotListPanel = ref(true)
const showCommentPanel = ref(false)
const searchKeyword = ref('')
// 定义景点数据接口
interface SpotData {
  OBJECTID: number;
  SpotName: string;
  SpotType: string;
  SpotIntroduction?: string;
  IntroduceImageBase64?: string;
  UserJsonData?: string;
}

const spots = ref<SpotData[]>([])
const selectedSpot = ref<SpotData | null>(null)
const spotComments = ref<{
  username: string;
  rating: number;
  content: string;
  timestamp: number;
}[]>([])

// 评论表单
const commentForm = ref({
  rating: 5,
  content: '',
})
const spotRating = computed(() => {
  const ratings: Record<number, number> = {}
  spots.value.forEach(spot => {
    ratings[spot.OBJECTID] = getSpotRating(spot.OBJECTID)
  })
  return ratings
})

// 计算属性：过滤后的景点列表
const filteredSpots = computed(() => {
  if (!searchKeyword.value) return spots.value
  const keyword = searchKeyword.value.toLowerCase()
  return spots.value.filter(spot =>
    spot.SpotName && spot.SpotName.toLowerCase().includes(keyword)
  )
})

// 计算属性：是否可以提交评论
const canSubmit = computed(() => {
  return commentForm.value.rating > 0 && commentForm.value.content.trim().length > 0
})

// 初始化地图
const initMap = async () => {
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
  })

  view = new MapView({
    container: 'commentMapView',
    map: map,
    center: [117.025711, 36.6752],
    zoom: 15,
    popup: {
      dockEnabled: true,
      dockOptions: {
        buttonEnabled: false,
        breakpoint: false,
      },
    },
  })

  // 定义景点图层
  attractionsLayer = new FeatureLayer({
    url: 'https://services5.arcgis.com/HfcuJ9RUSlysODB4/arcgis/rest/services/ScenicPoint/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: "unique-value",
      field: "SpotType",
      defaultSymbol: {
        type: "simple-marker",
        size: 14,
        color: [156, 156, 156, 0.8], // 默认灰色
        outline: {
          color: [255, 255, 255],
          width: 2
        }
      },
      uniqueValueInfos: [
        {
          value: "historical",
          symbol: {
            type: "simple-marker",
            style: "square",
            size: 14,
            color: [230, 97, 97, 0.8], // 红色系
            outline: {
              color: [255, 255, 255],
              width: 2
            }
          }
        },
        {
          value: "natural",
          symbol: {
            type: "simple-marker",
            style: "circle",
            size: 14,
            color: [75, 166, 127, 0.8], // 绿色系
            outline: {
              color: [255, 255, 255],
              width: 2
            }
          }
        },
        {
          value: "entertainment",
          symbol: {
            type: "simple-marker",
            style: "diamond",
            size: 14,
            color: [95, 150, 224, 0.8], // 蓝色系
            outline: {
              color: [255, 255, 255],
              width: 2
            }
          }
        }
      ]
    },
    // 添加标注
    labelingInfo: [{
      symbol: {
        type: "text",
        color: "#333333",
        haloColor: "#ffffff",
        haloSize: 2,
        font: {
          size: 12,
          weight: "normal"
        }
      },
      labelPlacement: "above-center",
      labelExpressionInfo: {
        expression: "$feature.SpotName"
      },
      minScale: 5000, // 当地图缩放到多少比例尺以内才显示标签
      maxScale: 0
    }]
  })
  map.add(attractionsLayer)

  // 添加点击事件监听器以选择要素
  view.on('click', async (event) => {
    const hitResults = (await view?.hitTest(event))?.results as __esri.MapViewGraphicHit[]
    const feature = hitResults.find((result) => result.layer?.id === attractionsLayer?.id)?.graphic

    if (feature) {
      const spotId = feature.attributes.OBJECTID
      const spot = spots.value.find(s => s.OBJECTID === spotId)
      if (spot) {
        selectSpot(spot)
      }
    }
  })
}

// 加载景点数据
const loadSpots = async () => {
  try {
    const query = attractionsLayer.createQuery()
    query.where = '1=1' // 查询所有记录
    query.outFields = ['*']

    const result = await attractionsLayer.queryFeatures(query)
    spots.value = result.features.map(feature => feature.attributes)

    // 高亮显示有评论的景点
    highlightSpotsWithComments()

    ElMessage.success(`已加载${spots.value.length}个景点`)
  } catch (error) {
    console.error('获取景点数据失败', error)
    ElMessage.error('获取景点数据失败')
  }
}

// 高亮显示有评论的景点
const highlightSpotsWithComments = () => {
  spots.value.forEach(spot => {
    if (spot.UserJsonData) {
      try {
        const userData = JSON.parse(spot.UserJsonData)
        if (userData.comments && userData.comments.length > 0) {
          // 在地图上添加高亮效果
          highlightSpotOnMap(spot.OBJECTID)
        }
      } catch (e) {
        console.error('解析用户数据失败', e)
      }
    }
  })
}

// 在地图上高亮显示景点
const highlightSpotOnMap = async (spotId: number) => {
  try {
    const query = attractionsLayer.createQuery()
    query.where = `OBJECTID = ${spotId}`
    query.returnGeometry = true

    const result = await attractionsLayer.queryFeatures(query)
    if (result.features.length > 0) {
      const feature = result.features[0]

      // 创建高亮符号
      const highlightSymbol = new SimpleMarkerSymbol({
        color: [255, 215, 0, 0.6], // 金色半透明
        size: 20,
        outline: {
          color: [255, 165, 0],
          width: 2
        }
      })

      // 创建图形并添加到地图
      const graphic = new Graphic({
        geometry: feature.geometry,
        symbol: highlightSymbol
      })

      // 添加到地图视图
      view.graphics.add(graphic)
    }
  } catch (error) {
    console.error('高亮景点失败', error)
  }
}

// 选择景点
const selectSpot = async (spot: SpotData) => {
  selectedSpot.value = spot
  showCommentPanel.value = true

  // 加载景点评论
  loadSpotComments(spot.OBJECTID)

  // 重置评论表单
  commentForm.value = {
    rating: 5,
    content: ''
  }

  // 缩放到景点位置
  zoomToSpot(spot.OBJECTID)
}

// 缩放到景点位置
const zoomToSpot = async (spotId: number) => {
  try {
    const query = attractionsLayer.createQuery()
    query.where = `OBJECTID = ${spotId}`
    query.returnGeometry = true

    const result = await attractionsLayer.queryFeatures(query)
    if (result.features.length > 0) {
      const feature = result.features[0]
      view.goTo({
        target: feature.geometry,
        zoom: 17
      })
    }
  } catch (error) {
    console.error('缩放到景点失败', error)
  }
}

// 加载景点评论
const loadSpotComments = (spotId: number) => {
  const spot = spots.value.find(s => s.OBJECTID === spotId)
  if (!spot) return

  try {
    if (spot.UserJsonData) {
      const userData = JSON.parse(spot.UserJsonData)
      spotComments.value = userData.comments || []
    } else {
      spotComments.value = []
    }
  } catch (e) {
    console.error('解析评论数据失败', e)
    spotComments.value = []
  }
}

// 提交评论
const submitComment = async () => {
  if (!selectedSpot.value) return
  if (!canSubmit.value) {
    ElMessage.warning('请填写评分和评价内容')
    return
  }

  try {
    // 准备评论数据
    const newComment = {
      username: userStore.username,
      rating: commentForm.value.rating,
      content: commentForm.value.content,
      timestamp: Date.now()
    }



    // 获取当前景点的用户数据
    let userData: UserData = {
      comments: []
    }
    if (selectedSpot.value.UserJsonData) {
      try {
        userData = JSON.parse(selectedSpot.value.UserJsonData) as UserData
      } catch (e) {
        userData = {
          comments: []
        }
      }
    }

    // 添加评论到用户数据
    if (!userData.comments) {
      userData.comments = []
    }
    userData.comments.push(newComment)

    // 计算平均评分
    const totalRating = userData.comments.reduce((sum: number, comment) => sum + comment.rating, 0)
    userData.averageRating = totalRating / userData.comments.length

    // 更新景点数据
    const attributes = {
      OBJECTID: selectedSpot.value.OBJECTID,
      UserJsonData: JSON.stringify(userData)
    }

    // 创建更新图形
    const updateFeature = new Graphic({
      attributes: attributes
    })

    // 应用编辑
    await attractionsLayer.applyEdits({
      updateFeatures: [updateFeature]
    })

    // 更新本地数据
    selectedSpot.value.UserJsonData = JSON.stringify(userData)
    loadSpotComments(selectedSpot.value.OBJECTID)

    // 更新景点列表中的数据
    const spotIndex = spots.value.findIndex(s => s.OBJECTID === selectedSpot.value!.OBJECTID)
    if (spotIndex !== -1) {
      spots.value[spotIndex].UserJsonData = JSON.stringify(userData)
    }

    // 高亮显示景点
    highlightSpotOnMap(selectedSpot.value.OBJECTID)

    // 重置表单
    commentForm.value = {
      rating: 5,
      content: ''
    }

    ElMessage.success('评价提交成功')
  } catch (error) {
    console.error('提交评价失败', error)
    ElMessage.error('提交评价失败')
  }
}

// 获取景点评分
const getSpotRating = (spotId: number) => {
  const spot = spots.value.find(s => s.OBJECTID === spotId)
  if (!spot || !spot.UserJsonData) return 0

  try {
    const userData = JSON.parse(spot.UserJsonData)
    return userData.averageRating || 0
  } catch (e) {
    return 0
  }
}

// 获取类型标签的样式
const getTypeTagType = (type: string = '') => {
  switch (type) {
    case 'historical':
      return 'danger'
    case 'natural':
      return 'success'
    case 'entertainment':
      return 'primary'
    default:
      return 'info'
  }
}

// 获取类型标签的文本
const getTypeLabel = (value: string = '') => {
  switch (value) {
    case 'historical':
      return '历史文化'
    case 'natural':
      return '自然风光'
    case 'entertainment':
      return '休闲娱乐'
    default:
      return value || '未分类'
  }
}

// 格式化日期
const formatDate = (timestamp: number) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 处理评论面板关闭
const handleCommentPanelClose = () => {
  // 重置评论表单
  commentForm.value = {
    rating: 5,
    content: ''
  }
}

onMounted(async () => {
  await initMap()
  await loadSpots()
})
</script>

<style scoped>
.comment-container {
  position: relative;
  height: 100vh;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.comment-map-view {
  width: 100%;
  height: 100%;
}

/* 功能按钮 */
.feature-panel-button {
  position: absolute;
  right: 20px;
  top: 20px;
  width: 44px;
  height: 44px;
  background: white;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  cursor: pointer;
  z-index: 10;
  transition: all 0.3s ease;
}

.feature-panel-button:hover {
  background: #f0f7ff;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

/* 抽屉样式 */
.custom-drawer :deep(.el-drawer__body) {
  padding: 0;
  overflow-y: auto;
}

.drawer-header {
  position: relative;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #f9fafc;
}

.close-button {
  position: absolute;
  right: 20px;
  top: 16px;
  cursor: pointer;
  color: #606266;
  transition: color 0.3s;
}

.close-button:hover {
  color: #409eff;
}

.drawer-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}

/* 搜索框 */
.search-box {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

/* 景点列表 */
.spot-list {
  padding: 0 16px;
}

.spot-item {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.spot-item:hover {
  background-color: #f5f7fa;
}

.spot-item.active {
  background-color: #ecf5ff;
  border-left: 3px solid #409eff;
}

.spot-info {
  flex: 1;
}

.spot-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #303133;
}

.spot-type {
  margin-top: 4px;
}

.spot-rating {
  min-width: 120px;
  text-align: right;
}

.no-rating {
  color: #909399;
  font-size: 14px;
}

/* 景点详情 */
.spot-detail {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.spot-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
  border-radius: 8px;
  margin-bottom: 16px;
}

.spot-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.spot-description {
  color: #606266;
  line-height: 1.6;
}

/* 评论列表 */
.comments-section {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.comments-section h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.comment-list {
  padding: 0 8px;
}

.comment-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.user-info {
  display: flex;
  align-items: center;
}

.username {
  margin-left: 8px;
  font-weight: 500;
  color: #303133;
}

.comment-content {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.average-rating {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  text-align: center;
}

/* 添加评论表单 */
.add-comment-section {
  padding: 16px;
}

.add-comment-section h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.no-comments {
  padding: 24px 16px;
  text-align: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .feature-panel-button {
    right: 10px;
    top: 10px;
  }
}
</style>
